import { defineStore } from "pinia";
import { RouteLocationNormalized } from "vue-router";
export const useTabbar = defineStore("tabbar", {
  state: () => {
    return {
      /**
       * 当前tabbar组件中的的路由集合
       */
      activeRouted: [] as RouteLocationNormalized[],
      /**
       * 当前激活的路由项
       */
      activeItem: {} as RouteLocationNormalized,
      /**
       * 当前激活的路由项下标
       */
      activeIndex: 0,
      /**
       * 被缓存的路由集合
       */
      inludeKeepAlive: [] as string[],
      /**
       * 路由缓存最大值
       */
      cacheMax: 10,
    };
  },
  getters: {},
  actions: {
    /**
     * 设置当前tabbar组件的路由集合数据
     * 包含设置当前激活的路由下标，
     * 设置当前激活的路由item
     * 设置存入需要缓存的路由页面
     * @param route:RouteLocationNormalized 当前激活的路由信息
     */
    setActiveRouted(route: RouteLocationNormalized): void {
      // 判断当前路由是否已经存在与tabbar中，false没有,则存入
      let bool = this.activeRouted.some((item) => {
        return item.fullPath === route.fullPath;
      });
      !route.meta.noTabbarShow && !bool ? this.activeRouted.push(route) : null;
      bool = this.activeRouted.some((item) => {
        return item.fullPath === route.fullPath;
      });
      // 判断当前路由是否在激活的tabbar集合中，如果在为：true
      if (bool) {
        // 获取当前激活路由下标
        this.activeIndex = this.activeRouted.findIndex((item) => item.fullPath === route.fullPath);
        // 获取当前激活路由
        this.activeItem = this.activeRouted[this.activeIndex];
        // 判断当前激活的路由页面是否需要被缓存，如果需要则存入缓存集合中
        if (this.activeItem.meta.keepAlive) {
          const isExsit = this.inludeKeepAlive.some(
            (routeName) => routeName === (this.activeItem.name as any as string)
          );
          if (!isExsit) {
            // 被缓存的路由数量是否超过最大缓存数？
            this.inludeKeepAlive.length >= this.cacheMax
              ? (this.inludeKeepAlive.shift(),
                this.inludeKeepAlive.push(this.activeItem.name as any as string))
              : this.inludeKeepAlive.push(this.activeItem.name as any as string);
          }
        }
      }
    },
    /**
     * 设置哪些路由需要被缓存
     * @param keepAlive 路由是否缓存
     * @param name 路由名称
     */
    setIncludeKeepAlive(keepAlive: boolean, name: string) {
      // 判断需要缓存，并缓存数组没有超过缓存最大值
      if (keepAlive && this.inludeKeepAlive?.length < this.cacheMax) {
        this.inludeKeepAlive.includes(name) ? null : this.inludeKeepAlive.push(name);
        // 判断需要缓存，并且缓存数组超过最大缓存值
      } else if (keepAlive && this.inludeKeepAlive?.length >= this.cacheMax) {
        this.inludeKeepAlive.includes(name)
          ? null
          : (this.inludeKeepAlive.shift(), this.inludeKeepAlive.push(name));
      }
    },
    /**
     * 删除已经被缓存的路由
     * @param route 路由对象
     */
    deleteIncludeKeepAlive(route: RouteLocationNormalized) {
      if (route.meta.keepAlive) {
        const idx = this.inludeKeepAlive.indexOf(route.name as any as string);
        idx > -1 ? this.inludeKeepAlive.splice(idx, 1) : null;
      }
    },
  },
  // persist: {
  //   enabled: true,
  // },
});
